﻿namespace LookupWithPicker
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using System.Reflection;

    public class SPFieldLookupWithPicker : SPFieldLookup
    {
        public SPFieldLookupWithPicker(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public SPFieldLookupWithPicker(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override bool AllowMultipleValues
        {
            get
            {
                return base.AllowMultipleValues;
            }

            set
            {
                base.AllowMultipleValues = value;
                Type t = typeof(SPFieldLookupWithPicker);
                MethodInfo mi = t.GetMethod("SetFieldAttributeValue", BindingFlags.Instance | BindingFlags.NonPublic);
                mi.Invoke(this, new object[] { "Type", "LookupWithPicker" });
            }
        }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                LookupWithPickerField fieldControl = new LookupWithPickerField();
                fieldControl.FieldName = this.InternalName;
                fieldControl.AllowMultipleValues = this.AllowMultipleValues;
                return fieldControl;
            }
        }

        public override object GetFieldValue(string value)
        {
            object res = base.GetFieldValue(value);
            return res;
        }

        public static string GetFieldValue(SPListItem item, string fieldName)
        {
            string val = "";
            if (item.Fields.ContainsField(fieldName) && item[fieldName] != null)
            {
                val = item[fieldName].ToString();
                switch (item.Fields.GetFieldByInternalName(fieldName).Type)
                {
                    case SPFieldType.Lookup:
                        val = new SPFieldLookupValue(val).LookupValue;
                        break;
                    case SPFieldType.User:
                        val = new SPFieldUserValue(item.Web, val).User.Name;
                        break;
                    case SPFieldType.Calculated:
                        val = new SPFieldMultiChoiceValue(val)[1];
                        break;
                }
            }

            return val;
        }
    }
}
